<template>
  <div class="home">
    <navbar></navbar>

    <van-tabs v-model="active" swipeable sticky>
      <van-tab v-for="(item,index) in category" :key="index" :title="item.title">
        <van-list
          v-model="item.loading"
          :finished="item.finished"
          finished-text="没有更多了"
          :immediate-check = "false"
          @load="onLoad"
        >
        <div class="detailparent">
          <detail class="detailitem" :detailitem="categoryitem" v-for="(categoryitem,categoryindex) in item.list" :key="categoryindex" />
        </div>
        </van-list>
      </van-tab>
    </van-tabs>

  </div>
</template>

<script>
import Navbar from "../components/common/Navbar";
import Detail from "./cover";
export default {
name: "Home",
  components: {Navbar,Detail},
  data(){
  return {
    category:[],
    active: 0
  }
  },
  methods:{
   async selectCategory(){
      const res = await this.$http.get('/category')
     this.changeCategory(res.data)
    },
    changeCategory(data){
      const mycategory = data.map((item,index)=>{
        item.list =[]
        item.page = 0
        item.pagesize = 10
        item.finished = false
        item.loading = false
        return item
      })
      this.category = mycategory
      this.selectArticle()
    },
    async selectArticle(){
     const categoryitem = this.catagoryItem()
      const res = await this.$http.get('/detail/' + categoryitem._id,{
        params:{
          page:categoryitem.page,
          pagesize:categoryitem.pagesize
        }
      })
      categoryitem.list.push(...res.data)
      categoryitem.loading = false
      if(res.data.length < categoryitem.pagesize){
        categoryitem.finished=true
      }
    },
    catagoryItem (){
     const  categoryitem = this.category[this.active]
      return categoryitem
    },
    onLoad(){
     const categoryitem = this.catagoryItem()
      setTimeout(()=>{
        categoryitem.page+=1
        this.selectArticle()
      },1000)
    },
  },
  watch:{
    active(){
      this.selectArticle()
    }
  },
  created() {
  this.selectCategory()
  }
}
</script>

<style scoped lang="less">
.home{
  background-color: white;
}
.detailparent{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  .detailitem{
    margin: 5px 0;
    width: 40%;
  }
}
</style>
